package com.abe.libquick.widget.tree;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.abe.libquick.R;

import java.util.ArrayList;
import java.util.List;

/*
 * 树数据源构造器
 */
@SuppressLint("InflateParams")
public class TreeViewAdapter extends BaseAdapter {
    private Context con;
    private LayoutInflater lif;
    private List<TreeViewNode> allsCache = new ArrayList<>();
    private List<TreeViewNode> alls = new ArrayList<>();
    private TreeViewAdapter oThis = this;
    private boolean hasCheckBox = true;// 是否拥有复选框
    private int expandedIcon = -1;
    private int collapsedIcon = -1;

    private boolean isCheckNode = true;

    /**
     * TreeAdapter构造函数
     *
     * @param context
     * @param rootNode 根节点
     */
    public TreeViewAdapter(Context context, TreeViewNode rootNode) {
        this.con = context;
        this.lif = (LayoutInflater) con
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        addNode(rootNode);
    }

    public List<TreeViewNode> getAllsCache() {
        return allsCache;
    }

    public void setAllsCache(List<TreeViewNode> allsCache) {
        this.allsCache = allsCache;
    }

    private void addNode(TreeViewNode node) {
        alls.add(node);
        allsCache.add(node);
        if (node.isLeaf())
            return;
        for (int i = 0; i < node.getChildren().size(); i++) {
            addNode(node.getChildren().get(i));
        }
    }

    // 复选框联动
    private void checkNode(TreeViewNode node, boolean isChecked) {
        node.setChecked(isChecked);
        for (int i = 0; i < node.getChildren().size(); i++) {
            checkNode(node.getChildren().get(i), isChecked);
        }
    }

    /**
     * 获得选中节点
     *
     * @return
     */
    public List<TreeViewNode> getSeletedNodes() {
        List<TreeViewNode> nodes = new ArrayList<TreeViewNode>();
        for (int i = 0; i < allsCache.size(); i++) {
            TreeViewNode n = allsCache.get(i);
            if (n.isChecked()) {
                nodes.add(n);
            }
        }
        return nodes;
    }

    /**
     * 获得选中节点
     *
     * @return
     */
    public void setSeletedNodes(String[] nodes) {
        for (String node : nodes) {
            for (int i = 0; i < allsCache.size(); i++) {
                TreeViewNode n = allsCache.get(i);
                if (n.getText().equals(node) && n.getChildren().size() <= 0) {
                    n.setChecked(true);
                    break;// 防止一个人属于多个组织引起的错误
                }
            }
        }
    }

    /**
     * 获得选中节点
     *
     * @return
     */
    public void setSeletedNodesByValues(String[] values) {
        for (String node : values) {
            for (int i = 0; i < allsCache.size(); i++) {
                TreeViewNode n = allsCache.get(i);
                if (n.getValue().equals(node)) {
                    n.setChecked(true);
                    break;
                }
            }
        }
    }

    // 控制节点的展开和折叠
    private void filterNode() {
        alls.clear();
        for (int i = 0; i < allsCache.size(); i++) {
            TreeViewNode n = allsCache.get(i);
            if (!n.isParentCollapsed() || n.isRoot()) {
                alls.add(n);
            }
        }
    }

    public boolean isCheckNode() {
        return isCheckNode;
    }

    /**
     * 设置是否复选框联动
     */
    public void setCheckNode(boolean isCheckNode) {
        this.isCheckNode = isCheckNode;
    }

    /**
     * 设置是否拥有复选框
     *
     * @param hasCheckBox
     */
    public void setCheckBox(boolean hasCheckBox) {
        this.hasCheckBox = hasCheckBox;
    }

    /**
     * 设置展开和折叠状态图标
     *
     * @param expandedIcon  展开时图标
     * @param collapsedIcon 折叠时图标
     */
    public void setExpandedCollapsedIcon(int expandedIcon, int collapsedIcon) {
        this.expandedIcon = expandedIcon;
        this.collapsedIcon = collapsedIcon;
    }

    /**
     * 设置展开级别
     *
     * @param level
     */
    public void setExpandLevel(int level) {
        alls.clear();
        for (int i = 0; i < allsCache.size(); i++) {
            TreeViewNode n = allsCache.get(i);
            if (n.getLevel() <= level) {
                if (n.getLevel() < level) {// 上层都设置展开状态
                    n.setExpanded(true);
                } else {// 最后一层都设置折叠状态
                    n.setExpanded(false);
                }
                alls.add(n);
            }
        }
        this.notifyDataSetChanged();
    }

    /**
     * 控制节点的展开和收缩
     *
     * @param position
     */
    public void ExpandOrCollapse(int position) {
        TreeViewNode n = alls.get(position);
        if (n != null) {
            if (!n.isLeaf()) {// 如果不是叶子节点
                n.setExpanded(!n.isExpanded());
                filterNode();
                this.notifyDataSetChanged();
            } else {// 如果是叶子节点
                if (n.isChecked()) {
                    n.setChecked(false);
                } else {
                    n.setChecked(true);
                }
                this.notifyDataSetChanged();
            }
        }
    }

    @Override
    public int getCount() {

        return alls.size();
    }

    @Override
    public Object getItem(int position) {

        return alls.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        ViewHolder holder;
        if (view == null) {
            view = this.lif.inflate(R.layout.listview_item_tree, null);
            holder = new ViewHolder();
            holder.ivExEc = view.findViewById(R.id.ivExEc);
            holder.chbSelect = view.findViewById(R.id.chbSelect);
            // 复选框单击事件
            holder.chbSelect.setOnClickListener(v -> {
                TreeViewNode n = (TreeViewNode) v.getTag();
                if (isCheckNode) {
                    checkNode(n, ((CheckBox) v).isChecked());
                }
                oThis.notifyDataSetChanged();
            });
            holder.ivIcon = view.findViewById(R.id.ivIcon);
            holder.tvOrgName = view.findViewById(R.id.tvText);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        // 得到当前节点
        TreeViewNode n = alls.get(position);

        if (n != null) {
            holder.chbSelect.setTag(n);
            holder.chbSelect.setChecked(n.isChecked());

            // 是否显示复选框
            if (n.hasCheckBox() && hasCheckBox) {
                holder.chbSelect.setVisibility(View.VISIBLE);
            } else {
                holder.chbSelect.setVisibility(View.GONE);
            }

            // 是否显示图标
            if (n.getIcon() == -1) {
                holder.ivIcon.setVisibility(View.GONE);
            } else {
                holder.ivIcon.setVisibility(View.VISIBLE);
                holder.ivIcon.setImageResource(n.getIcon());
            }

            // 显示文本
            holder.tvOrgName.setText(n.getText());
            if (n.isLeaf()) {
                // 是叶节点 不显示展开和折叠状态图标
                holder.ivExEc.setVisibility(View.GONE);
            } else {
                // 单击时控制子节点展开和折叠,状态图标改变
                holder.ivExEc.setVisibility(View.VISIBLE);
                if (n.isExpanded()) {
                    if (expandedIcon != -1)
                        holder.ivExEc.setImageResource(expandedIcon);
                } else {
                    if (collapsedIcon != -1)
                        holder.ivExEc.setImageResource(collapsedIcon);
                }
            }
            // 控制缩进
            view.setPadding(48 * n.getLevel(), 3, 3, 3);
        }
        return view;
    }

    /*
     * 列表项控件集合
     */
    public class ViewHolder {
        ImageView ivExEc;// 展开或折叠标记"+"或"-"
        CheckBox chbSelect;// 选中与否
        ImageView ivIcon;// 图标
        TextView tvOrgName;// 文本
    }
}